﻿using SanJ.FreeCare.Abp.Authorization.Users;
using SanJ.FreeCare.Abp.Chat;
using SanJ.FreeCare.Chat;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Entities.Events;
using Volo.Abp.EventBus;
using Volo.Abp.ObjectMapping;

namespace SanJ.FreeCare.Friendships.Cache
{
    public class UserFriendCacheSyncronizer :
        ILocalEventHandler<EntityCreatedEventData<Friendship>>,
        ILocalEventHandler<EntityDeletedEventData<Friendship>>,
        ILocalEventHandler<EntityUpdatedEventData<Friendship>>,
        ILocalEventHandler<EntityCreatedEventData<ChatMessage>>,
        ITransientDependency
    {
        private readonly IUserFriendsCache _userFriendsCache;
        private readonly IObjectMapper _objectMapper;

        public UserFriendCacheSyncronizer(
            IUserFriendsCache userFriendsCache,
            IObjectMapper objectMapper)
        {
            _userFriendsCache = userFriendsCache;
            _objectMapper = objectMapper;
        }

        public Task HandleEventAsync(EntityCreatedEventData<Friendship> eventData)
        {
            _userFriendsCache.AddFriend(
                eventData.Entity.ToUserIdentifier(),
                _objectMapper.Map<Friendship, FriendCacheItem >(eventData.Entity)
                );
            return Task.CompletedTask;
        }

        public Task HandleEventAsync(EntityDeletedEventData<Friendship> eventData)
        {
            _userFriendsCache.RemoveFriend(
                eventData.Entity.ToUserIdentifier(),
                _objectMapper.Map<Friendship, FriendCacheItem>(eventData.Entity)
            );
            return Task.CompletedTask;
        }

        public Task HandleEventAsync(EntityUpdatedEventData<Friendship> eventData)
        {
            var friendCacheItem = _objectMapper.Map<Friendship, FriendCacheItem>(eventData.Entity);
            _userFriendsCache.UpdateFriend(eventData.Entity.ToUserIdentifier(), friendCacheItem);
            return Task.CompletedTask;
        }


        public Task HandleEventAsync(EntityCreatedEventData<ChatMessage> eventData)
        {
            var message = eventData.Entity;
            if (message.ReadState == ChatMessageReadState.Unread)
            {
                _userFriendsCache.IncreaseUnreadMessageCount(
                    new UserIdentifier(message.TenantId, message.UserId),
                    new UserIdentifier(message.TargetTenantId, message.TargetUserId),
                    1
                );
            }
            return Task.CompletedTask;
        }

    }
}
